//
//  ClockView.m
//  MooreDoll
//
//  Created by Orange on 2014/12/25.
//  Copyright (c) 2014年 Tank. All rights reserved.
//


#define kCOLOR_BULE  [UIColor colorWithRed:0.203922F green:0.631373F blue:0.862745F alpha:1.0F]
#define kCOLOR_GRAY  [UIColor grayColor]
#define kCOLOR_BLACK [UIColor blackColor]
#define kCOLOR_WHITE [UIColor whiteColor]

#define ActionSheet1 @"響鈴十次"
#define ActionSheet2 @"搖一搖"
#define ActionSheet3 @"內建鈴聲"
#define ActionSheet4 @"錄音"
#define ActionSheet5 @"手機音樂"

#import "BeasCollectionViewDataSource.h"
#import "ClockView.h"
#import "ClockCell.h"
#import "UserDefaults.h"
#import "ConfigOfKey.h"

@interface ClockView()<UICollectionViewDelegate,UIActionSheetDelegate>
@property (nonatomic, strong) BeasCollectionViewDataSource *dataSource;
@property (nonatomic, strong) NSArray *list;
@property (nonatomic) BOOL clockState;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;

@property (weak, nonatomic) IBOutlet UITextField *textYYMMDD;
@property (weak, nonatomic) IBOutlet UITextField *textTime;
@property (weak, nonatomic) IBOutlet UIButton *buttonClockMusic;
@property (weak, nonatomic) IBOutlet UIButton *buttonClockStop;
@property (weak, nonatomic) IBOutlet UILabel *labelTime;
@property (weak, nonatomic) IBOutlet UILabel *labelRestart;
@property (weak, nonatomic) IBOutlet UILabel *labelClockMusic;
@property (weak, nonatomic) IBOutlet UILabel *labelClockStop;


@property (strong, nonatomic) UIDatePicker       *dateModeDay;
@property (strong, nonatomic) UIDatePicker       *dateModeTime;
@property (strong, nonatomic) NSMutableArray     *selectedWeek;
@end

@implementation ClockView

- (void)drawRect:(CGRect)rect {
    [super drawRect: rect];
    _list = @[@"一",@"二",@"三",@"四",@"五",@"六",@"日"];

    [self initialization];
}
- (void) clockStateOn: (BOOL) clock {
    [self setClockState: clock];
    [self clockViewChange: clock];
    [_collectionView reloadData];
}
- (void) clockSelectedWeek: (NSArray *) array atYYMMDD:(NSString *) yymmdd atTime:(NSString *) times{
    _selectedWeek =  [NSMutableArray array] ;

    for (id obj in array) {
        [_selectedWeek addObject: obj];
    }
    [_textYYMMDD setText: yymmdd];
    [_textTime   setText: times];
    [_collectionView reloadData];
}
- (void) clockViewChange:(BOOL) clock {
    UIColor * color ;
    if (clock)
        color = kCOLOR_BLACK;
    else
        color = kCOLOR_GRAY;
    
    [_textYYMMDD setTextColor: color];
    [_textTime   setTextColor: color];
    
    [_labelTime         setTextColor: color];
    [_labelRestart      setTextColor: color];
    [_labelClockMusic   setTextColor: color];
    [_labelClockStop    setTextColor: color];
    
    [_buttonClockMusic  setTitleColor: color forState: UIControlStateNormal];
    [_buttonClockStop   setTitleColor: color forState: UIControlStateNormal];
    [_buttonClockMusic  setEnabled: clock];
    [_buttonClockStop   setEnabled: clock];
}
#pragma mark - init
- (void) initialization {
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    [layout setItemSize: CGSizeMake(50, 50)];
    [layout setScrollDirection: UICollectionViewScrollDirectionVertical];
    
    _dataSource = [[BeasCollectionViewDataSource alloc]initWithItems: _list
                                                      cellIdentifier: kClockCell
                                                  configureCellBlock: ^(ClockCell *cell, id item ) {
                                                      [cell clockSelectedCell: item ];
    }];
    [_collectionView setDataSource: _dataSource];
    [_collectionView setDelegate: self];
    [_collectionView registerNib: [ClockCell nib] forCellWithReuseIdentifier: _dataSource.cellIdentifier];
    [_collectionView setCollectionViewLayout: layout];

    [self initializationTextAndTime];
}
- (void) initializationTextAndTime {
    if (!_dateModeDay ) _dateModeDay  = [[UIDatePicker alloc]init];
    if (!_dateModeTime) _dateModeTime = [[UIDatePicker alloc]init];
    
    [self textFieldSet: _textYYMMDD setDateMode: UIDatePickerModeDate inDatePicker: _dateModeDay];
    [self textFieldSet: _textTime   setDateMode: UIDatePickerModeTime inDatePicker: _dateModeTime];
}
#pragma mark - IBAction
- (IBAction)saveClockPress: (id)sender {

    
    if ( _delegate && [_delegate respondsToSelector: @selector(clockViewSavePress:atYYMMDD:atTime:)]) {
        [_delegate clockViewSavePress: _selectedWeek atYYMMDD: _textYYMMDD.text atTime: _textTime.text];
    }
}
- (IBAction)clearClockPress: (id)sender {
    if ( _delegate && [_delegate respondsToSelector: @selector(clockViewClearPress)]) {
        [_delegate clockViewClearPress];
    }
}
- (IBAction)stopClockAction: (id)sender {
    UIActionSheet *sheet =[ [UIActionSheet alloc]initWithTitle: @"停止方式"
                                                      delegate: self
                                             cancelButtonTitle: nil
                                        destructiveButtonTitle: nil
                                             otherButtonTitles: ActionSheet1,ActionSheet2, nil];
    [sheet showInView: self];
    
    if ( _delegate && [_delegate respondsToSelector: @selector(clockViewStopAction)]) {
        [_delegate clockViewStopAction];
    }
}
- (IBAction)changeClockMusicPress: (id)sender {
    UIActionSheet *sheet =[ [UIActionSheet alloc]initWithTitle: ActionSheet3
                                                      delegate: self
                                             cancelButtonTitle: nil
                                        destructiveButtonTitle: nil
                                             otherButtonTitles: ActionSheet3,ActionSheet4,ActionSheet5, nil];
    [sheet showInView: self];
    
    if ( _delegate && [_delegate respondsToSelector: @selector(clockViewChangeMusic)]) {
        [_delegate clockViewChangeMusic];
    }
}
#pragma mark - TextField
- (void) textFieldSet: (UITextField *) textFie setDateMode: (UIDatePickerMode ) dateMode inDatePicker:(UIDatePicker *) datePicker{
    UIToolbar       *toolBar    = [[UIToolbar alloc] initWithFrame: CGRectMake(0, 0, self.frame.size.width , 44)];
    UIBarButtonItem *flexSpace  = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemFlexibleSpace
                                                                                target: nil
                                                                                action: nil];
    UIBarButtonItem *cancelBut  = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemCancel
                                                                                target: self
                                                                                action: @selector(cancelPicker)];
    UIBarButtonItem *saveBut    = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemDone
                                                                                target: self
                                                                                action: @selector(savePicker:)];
    [flexSpace  setWidth: 5.0];
    [datePicker setDatePickerMode: dateMode];
    [toolBar    setItems: @[ cancelBut , flexSpace , saveBut]];
    
    [textFie setInputView: datePicker];
    [textFie setInputAccessoryView: toolBar];
}
- (void) cancelPicker {
    [self textFielResignFirstResponder];
}
- (void) savePicker:(id) sneder {
    [self textFielResignFirstResponder];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    [formatter setDateFormat: @" yyyy / MM / dd"];
    [_textYYMMDD setText: [NSString stringWithFormat: @"%@",[formatter stringFromDate: _dateModeDay.date]]];
    
    [formatter setDateFormat: @" HH : mm"];
    [_textTime   setText: [NSString stringWithFormat: @"%@",[formatter stringFromDate: _dateModeTime.date]]];
}
- (void) textFielResignFirstResponder {
    [_textTime resignFirstResponder];
    [_textYYMMDD resignFirstResponder];
}
#pragma mark - Collection Delegate 

- (void) collectionView :(UICollectionView *)collectionView didSelectItemAtIndexPath: (NSIndexPath *)indexPath{
    if (_clockState) {
        ClockCell* cell = [self cellForItme: indexPath];
        cell.backgroundColor = [self changeClockSelectedItmeDay: indexPath];
    }
}
- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
    cell.backgroundColor = kCOLOR_WHITE;

    if ([self selectedcellNotExist: indexPath]) {
        cell.backgroundColor = [self cellBackgroundColorSet: _clockState];
    }
}

#pragma mark - Collection Delegate Use
- (BOOL) selectedcellNotExist: (NSIndexPath *) indexPath {
    for (id selectedItem in _selectedWeek) {
        if ([selectedItem isEqualToString: [self listAtIndex: indexPath]]) return YES;
    }
    return NO;
}
- (UIColor *) cellBackgroundColorSet :(BOOL) clock{
    if(clock)
        return kCOLOR_BULE;
    else
        return kCOLOR_GRAY;
}
- (ClockCell *) cellForItme:(NSIndexPath *) indexPath {
    return (ClockCell *)[_collectionView cellForItemAtIndexPath:indexPath];
}
- (UIColor *) changeClockSelectedItmeDay: (NSIndexPath *) indexPath {
    id listItem = [self listAtIndex: indexPath];
    for (id selectedItem in _selectedWeek) {
        if ([selectedItem isEqualToString: listItem]) {
            [_selectedWeek removeObject: listItem];
            return kCOLOR_WHITE ;
        }
    }
    [_selectedWeek addObject: listItem];
    return kCOLOR_BULE;
}
- (id) listAtIndex: (NSIndexPath *) indexPath{
    return [ _list objectAtIndex: indexPath.row ];
}
#pragma mark - actionSheet Delegate
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if ([actionSheet.title isEqualToString: ActionSheet3]){
        [_buttonClockMusic setTitle: [actionSheet buttonTitleAtIndex: buttonIndex] forState: UIControlStateNormal];
        switch ( buttonIndex ) {
            case 0:
                [self systemMusicSelect];
                break;
            case 1:
                [self recoderForMe];
                break;
            case 2:
                [self localMusicSelect];
                break;
        }
    }
    else{
        [_buttonClockStop  setTitle: [actionSheet buttonTitleAtIndex: buttonIndex] forState: UIControlStateNormal];
        [UserDefaults set: [NSNumber numberWithBool: buttonIndex] withKey: kUserDefaultsClockStopStyle];
    }
}
- (void) systemMusicSelect {
    if ( _delegate && [_delegate respondsToSelector: @selector(clockViewSystemMusicSelect)]) {
        [_delegate clockViewSystemMusicSelect];
    }
}
- (void) recoderForMe {
    if ( _delegate && [_delegate respondsToSelector: @selector(clockViewRecoderForMe)]) {
        [_delegate clockViewRecoderForMe];
    }
}
- (void) localMusicSelect {
    if ( _delegate && [_delegate respondsToSelector: @selector(clockViewLocalMusicSelect)]) {
        [_delegate clockViewLocalMusicSelect];
    }
}
@end
